<template>
  <div class="page">
    <!--连接-->
    <div class="ip">
      <el-input size="small" placeholder="连接IP和端口" readonly v-model="ipAddress"> </el-input>
    </div>
    <div class="pageItem">
      <el-button class="btn" type="primary" size="small" @click="reloadWss">重启服务</el-button>
    </div>
    <el-select size="small" class="pageItem" v-if="isShowKey" v-model="selectKey"  @change="changeKey" placeholder="选择客户端" no-data-text="没有任何连接">
      <el-option
          v-for="(item) in clientList"
          :key="item.ip"
          :label="item.ip"
          :value="item.ip">
      </el-option>
    </el-select>
    <div class="pageItem">
      <el-button class="btn" type="primary" size="small" @click="cutScreen">截图</el-button>
    </div>

  </div>
</template>

<script>
import {mapState ,mapGetters} from "vuex"
import {ipcRenderer} from "electron";
import { ElMessage } from 'element-plus'

export default {
  name: "auTabber",
  data(){
    return {
      isShowKey:true
    }
  },
  computed:{
    ...mapState({
      ipAddress: (state) => {
        return state.ipAddress||"获取失败"
      },
      clientList: state => state.clientList,
      selectKey: state => state.clientSelectKey,
    }),
    ...mapGetters(["thenData","thenClient"])
  },
  watch:{
    selectKey(){
      this.isShowKey=false;
      this.$nextTick(()=>{
        this.isShowKey=true;
      })
    }
  },
  methods:{
    changeKey(val){
      this.$store.commit('setClientSelectKey',val);
    },
    reloadWss(){
      //清空变量
      this.selectKey=null;
      this.$store.commit('setClient', []);
      //重启
      ipcRenderer.invoke("wss-reload").then(e=>console.log(e));
      //重新获取ip
      ipcRenderer.invoke("wss-init").then(info => {
        this.$store.commit('setIpAddress', info.ip);
        this.$store.commit('setClient', info.clients);
    });
    },
    cutScreen(){
      //截图
      if(!this.selectKey){
        return ElMessage.error("请选择客户端");
      }
      const loading = this.$loading({
        lock: true,
        text: '获取中...',
      });
      let timer=setInterval(()=>{
        if(!this.selectKey){
          loading.close();
          clearInterval(timer);
          return ElMessage.error("客户端连接已断开");
        }
      },500);
      ipcRenderer.invoke("wss-send-wait",{
        ip:this.selectKey,
        code:202
      }).then((e)=>{
        console.log(e)
        loading.close();
        clearInterval(timer);
        if(e.code==200){
          this.$store.commit("addData",{
            title:new Date().getTime(),
            image:e.info,
            id:e.id
          })
        }else{
          ElMessage.error(e.info);
        }
        
      });
    }
  },
  created() {

  }
}
</script>

<style scoped lang="scss">
  .page{
    padding: 8px;
    font-size: 14px;
  }
  .pageItem{
    margin-top: 8px;
  }
  .btn{
    width: 100%;
  }
</style>
